package cn.evun.sweet.demo.extend;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.Authority;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.usermanager.ClearTextPasswordEncryptor;
import org.apache.ftpserver.usermanager.PasswordEncryptor;
import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;
import org.apache.ftpserver.usermanager.impl.BaseUser;
import org.apache.ftpserver.usermanager.impl.ConcurrentLoginPermission;
import org.apache.ftpserver.usermanager.impl.TransferRatePermission;
import org.apache.ftpserver.usermanager.impl.WritePermission;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import cn.evun.sweet.common.util.DateUtils;
import cn.evun.sweet.common.util.StringUtils;
import cn.evun.sweet.core.file.FileUtils;
/**
 * <p> ftp服务端 在应用开启关闭时 启动ftp服务器或删除历史文件
 * 
 * @see http://mina.apache.org/ftpserver-project/embedding_ftpserver.html
 * 
 * @author zhouhb
 * @since V1.0.0
 */
public class FtpFileServerLister implements ServletContextListener {

	protected static final Logger LOGGER = LogManager.getLogger();
	
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		
		ServletContext ctx = sce.getServletContext();
		
		String port = "2221";
		InputStream in = null;
		String newUserPath = "ftpserver-" + DateUtils.getToday() + ".properties";
		String userPath = null;			//用户配置信息
		String homePath = "ftpserver/home";			//ftp服务器路径
		boolean hasUserPath = false;
		String separator  = FileUtils.getFileSeparator();
		
		try {//是否启动ftp服务器
			Properties prop = new Properties();	
			in = FtpFileServerLister.class.getClassLoader().getResourceAsStream("conf/sweeter-config.properties");
			prop.load(in);
			String enable = prop.getProperty("file.ftpserver.enable");
			userPath = prop.getProperty("file.ftpserver.userpath");
			port = prop.getProperty("file.ftpserver.port");
			if(!"true".equals(enable)){
				return;
			}
		} catch (Exception e) {
			LOGGER.error(e.getMessage());
		} finally{
			try {
				in.close();
			} catch (Exception e) {
				
			}
		}
		
		FileOutputStream ot = null;
		try {//读写ftp用户的配置信息
			Properties prop = new Properties();
			String realPath = ctx.getRealPath(userPath);
			in = new FileInputStream(new File(realPath));
			if(in != null && in.available() > 0){
				hasUserPath = true;
				prop.load(in);
				Set<Object> keys = prop.keySet();
				Iterator<Object> ite = keys.iterator();
				while(ite.hasNext()){
					String key = (String) ite.next();
					//将路径转换为绝对路径
					if(key.indexOf("homedirectory") != -1){
						String path = ctx.getRealPath(prop.getProperty(key));
						if(StringUtils.isEmpty(path)){//不存在则创建
							new File(ctx.getRealPath("") + separator + prop.getProperty(key)).mkdir();
						}
						prop.setProperty(key, ctx.getRealPath(prop.getProperty(key)));
					}
				}
				
				newUserPath = realPath.substring(0,realPath.lastIndexOf(separator) + 1)+newUserPath;
				ot = new FileOutputStream(new File(newUserPath));
				prop.store(ot, "");
			}
		} catch (Exception e) {
			LOGGER.error(e.getMessage());
		} finally{
			try {
				ot.close();
			} catch (Exception e) {
				
			}
			try {
				in.close();
			} catch (Exception e) {
				
			}
		}
		
		try {
			FtpServerFactory serverFactory = new FtpServerFactory();
			ListenerFactory factory = new ListenerFactory();
			PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
			// set the port of the listener
			factory.setPort(Integer.parseInt(port));
			// replace the default listener
			serverFactory.addListener("default", factory.createListener());
			//密码采用明文
			PasswordEncryptor passwordEncryptor = new ClearTextPasswordEncryptor();
			userManagerFactory.setPasswordEncryptor(passwordEncryptor);
			
			if(hasUserPath){
				userManagerFactory.setFile(new File(newUserPath));
				serverFactory.setUserManager(userManagerFactory.createUserManager());
			}else{
				UserManager um = userManagerFactory.createUserManager();
				BaseUser user = new BaseUser();
				List<Authority> list = new ArrayList<Authority>();
				list.add(new WritePermission());
				list.add(new TransferRatePermission(0,0));
				list.add(new ConcurrentLoginPermission(0,0));
				user.setAuthorities(list);
				user.setName("admin");
				user.setPassword("Aa123456");
				user.setHomeDirectory(ctx.getRealPath(homePath));
				um.save(user);
				File file = new File(ctx.getRealPath("") + separator + homePath);
				if(!file.exists()){
					file.mkdir();
				}
				serverFactory.setUserManager(um);
			}
			
			FtpServer server = serverFactory.createServer();
			
			// start the server
			server.start();
		} catch (FtpException e) {
			LOGGER.error("FTP服务器启动失败:" + e.getMessage());
		}
//		userManagerFactory.setFile(new File(ctx.getRealPath("ftpserver/users.properties")));
//		serverFactory.setUserManager(userManagerFactory.createUserManager());
		// start the server
		
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		
	}

}
